package com.photoprint;


import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageView.ScaleType;

public class PhotoPreviewActivity extends BaseActivity implements
	AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {

	private Cursor thumbCursor;
	private Cursor imageCursor;
	private ArrayList<Photo> thumbnailsDataList;
	
	private Gallery gallery;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.photo_preview_activity);

        mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
        mSwitcher.setFactory(this);
        mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));

        initData();
        gallery = (Gallery) findViewById(R.id.gallery);
        gallery.setAdapter(new ImageAdapter(this));
        gallery.setOnItemSelectedListener(this);
    }
	
	
    @Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Intent i = getIntent();
		if(i != null ){
			int num = i.getIntExtra("num", 1);
			gallery.setSelection(num);
		}
		
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(thumbCursor != null){
			thumbCursor.close();
			thumbCursor = null;
		}
		if(imageCursor != null){
			imageCursor.close();
			imageCursor = null;
		}
	}



	public void onItemSelected(AdapterView parent, View v, int position, long id) {
    	mSwitcher.setImageDrawable(new BitmapDrawable(BitmapFactory.decodeFile(thumbnailsDataList.get(position).getThumb_data())));
//    	mSwitcher.setBackgroundDrawable(((ImageView)v).getBackground());
    }

    public void onNothingSelected(AdapterView parent) {
    }

    public View makeView() {
        ImageView i = new ImageView(this);
        i.setBackgroundColor(0xFF000000);
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT));
        return i;
    }

    private ImageSwitcher mSwitcher;

    public class ImageAdapter extends BaseAdapter {
        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return thumbnailsDataList.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = null;
            if(convertView == null){
            	i = new ImageView(mContext);
            }else {
            	i = (ImageView)convertView;
            }
            Bitmap b = BitmapFactory.decodeFile(thumbnailsDataList.get(position).getThumb_data());
            i.setImageBitmap(toRoundCorner(b,20));
            i.setAdjustViewBounds(true);
            i.setScaleType(ScaleType.FIT_CENTER);
            i.setLayoutParams(new Gallery.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            i.setPadding(5, 5, 5, 5);
            i.setBackgroundResource(R.drawable.picture_frame);
            return i;
        }

        private Context mContext;

    }
    
    /**
	 * 图片转圆角
	 * @param bitmap
	 * @param pixels
	 * @return
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) { 
	       Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap 
	                .getHeight(), Config.ARGB_8888); 
	        Canvas canvas = new Canvas(output); 
	 
	        final int color = 0xff424242; 
	        final Paint paint = new Paint(); 
	        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); 
	        final RectF rectF = new RectF(rect); 
	        final float roundPx = pixels; 
	 
	        paint.setAntiAlias(true); 
	        canvas.drawARGB(0, 0, 0, 0); 
	        paint.setColor(color); 
	        canvas.drawRoundRect(rectF, roundPx, roundPx, paint); 
	      
	        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));  
	        canvas.drawBitmap(bitmap, rect, rect, paint); 
	 
	        return output; 
	}

    public void initData(){
		if(thumbCursor == null){
			thumbCursor = this.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
					new String[]{MediaStore.Images.Thumbnails.DATA,MediaStore.Images.Thumbnails.IMAGE_ID}, null, null, null);
		}else{
			thumbCursor.requery();
		}
		
		if(thumbnailsDataList == null){
			thumbnailsDataList = new ArrayList<Photo> ();
		}else{
			thumbnailsDataList.clear();
		}
		
		if(thumbCursor.moveToFirst()){
			do{
				Photo photo = new Photo();
				photo.setThumb_data(thumbCursor.getString(thumbCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA)));
				photo.setImage_id(thumbCursor.getString(thumbCursor.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID)));
				//图片的绝对地址
				imageCursor = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						new String[]{MediaStore.Images.Media.DATA}, MediaStore.Images.Media._ID+"="+photo.getImage_id(), null, null);
				if(imageCursor != null && imageCursor.moveToFirst()){
					photo.setImage_data(imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA)));
					Log.e("initData", photo.getImage_data());
				}
				imageCursor.close();
				imageCursor = null;
				thumbnailsDataList.add(photo);
			}while(thumbCursor.moveToNext());
		}
	}
    
}
